#!/usr/bin/env python
# -*- coding: utf-8 -*-
# title       :
# author      : jarry
import os
import sys

from .InitQtModule import *
# from JTK.jcore.Qt import *

# from unipath import Path
from JTK.jcore.JPath import JPath
# from pyLibs.python3.PySide2.QtCore import Signal

from ..data import utils

try:
    import maya.cmds as cmds
    import pymel.core as pm
except:
    pass
from . import __file__ as _initpy_file

__CURRENT_PATH__ = os.path.dirname(os.path.realpath(_initpy_file))


class AovListWidget(QListWidget):
    dropped = Signal(list)

    def __init__(self, parent=None):
        super(AovListWidget, self).__init__(parent)
        self.parent = parent
        # self.setDragEnabled(True)
        # self.setDragDropMode(QAbstractItemView.DragDrop)
        # self.setDropIndicatorShown(True)
        # self.setAcceptDrops(True)
        # 拖拽参考 https://blog.csdn.net/qissme/article/details/109183951

        self.setSelectionMode(QListWidget.ExtendedSelection)
        self.doubleClicked.connect(self.select_aov)

    def update(self):
        for item in self.items():
            if self.parent.objectName() == 'AOVActiveItemWidget':
                item.setCheckState(Qt.Checked)

            icon_path = JPath(__CURRENT_PATH__).parent.child('data').child('icons').child('%s.png' % item.text())
            if icon_path.exists():
                item.setIcon(QIcon(icon_path))
            aov_node_name = 'aiAOV_%s' % item.text()
            #print '1',aov_node_name

            if cmds.objExists(aov_node_name):
                #print '2',aov_node_name
                font = item.font()
                font.setBold(True)
                brush = QBrush()
                brush.setColor(QColor(0, 255, 0))

                if cmds.getAttr('%s.enabled' % aov_node_name):
                    item.setCheckState(Qt.Checked)
                else:
                    item.setCheckState(Qt.Unchecked)
                    # item =QListWidgetItem
                    # item.checkState()
                if cmds.getAttr('%s.lightGroups' % aov_node_name):
                    brush.setColor(QColor(250, 255, 0))
                    # item = QStandardItem()
                    bg_brush = QColor(120, 120, 0, 10)
                    item.setBackground(QColor(120, 120, 0, 10))
                    item.setForeground(QColor(250, 255, 0))

                else:
                    bg_brush = QColor(0, 0, 0, 0)
                    item.setBackground(QColor(0, 0, 0, 0))
                    item.setForeground(QColor(0, 255, 0))

                #item.setForeground(brush)
                item.setFont(font)
                #item.setBackground(bg_brush)


            else:
                font = item.font()
                font.setBold(False)

                item.setFont(font)
                brush = QBrush()
                brush.setColor(QColor(200, 200, 200))
                item.setForeground(brush)

    def items(self):
        items = []

        for item in self._items():
            items.append(item)
        return items

    def _items(self):
        """
        Return a list of all the items in the tree widget.
        返回所有item
        :rtype: lsit[studioqt.TreeWidgetItem]
        """
        return self.findItems(
            "*",
            Qt.MatchWildcard | Qt.MatchRecursive
        )

    def texts(self):
        texts = []
        for i in self.items():
            texts.append(i.text())
        return texts

    def item_from_text(self, text):
        for item in self.items():
            if text == item.text():
                return item

    def text_row(self, text):
        texts = self.texts()
        if text in texts:
            row = texts.index(text)
            return row

    def takeText(self, text):
        for i in self.items():
            if text == i.text():
                self.takeItem(self.row(i))

    def selected_texts(self):
        texts = []
        items = self.selectedItems()
        for i in items:
            texts.append(i.text())
        return texts

    # def set_select_texts(self, texts):
    #     for text in texts:
    #         row = self.row_from_text(text)
    #         # index = self.index_from_text(text)
    #         print row
    #         item = self.item(row)
    # item.setSelected(True)
    # print item
    # print item.text()
    # self.setSelection(item)
    # print QItemSelectionModel.SelectionFlags
    # self.setCurrentRow(row, QItemSelectionModel.SelectionFlags)

    def contextMenuEvent(self, event):
        """
        显示右键按钮

        :type event: QtCore.QEvent
        :rtype: None
        """
        menu = self.createItemsMenu()
        point = QCursor.pos()
        return menu.exec_(point)

    def createItemsMenu(self):
        """
        创建右键菜单
        :rtype: QtWidgets.QMenu
        """
        items = self.selectedItems()

        menu = QMenu(self)

        if items:
            try:
                if self.parent.objectName() == 'AOVActiveItemWidget':
                    checkItemAction = QAction(u'勾选选中的列表', menu)
                    checkItemAction.triggered.connect(self.check_select_item)
                    unCheckItemAction = QAction(u'取消勾选选中的列表', menu)
                    unCheckItemAction.triggered.connect(self.uncheck_select_item)

                    removeItemAction = QAction(u'删除选中的AOV', menu)
                    removeItemAction.triggered.connect(self.remove_aov_select_item)

                    AdjustmentItemAction = QAction(u'旧渲染层-创建Enbal层覆盖', menu)
                    AdjustmentItemAction.triggered.connect(self.adjustment_enbal)

                    selectAovItemAction = QAction(u'在maya选择中列表中的Aov', menu)
                    selectAovItemAction.triggered.connect(self.select_aov)

                    setAllLightGroupOnItemAction = QAction(u'设置AllLightGroup开启', menu)
                    setAllLightGroupOnItemAction.triggered.connect(lambda: self.set_all_lightgroup(True))

                    setAllLightGroupOffItemAction = QAction(u'设置AllLightGroup关闭', menu)
                    setAllLightGroupOffItemAction.triggered.connect(lambda: self.set_all_lightgroup(False))
                    menu.addAction(checkItemAction)

                    menu.addAction(unCheckItemAction)
                    menu.addAction(removeItemAction)

                    menu.addAction(AdjustmentItemAction)
                    menu.addAction(selectAovItemAction)
                    if items[0].text() not in ['P', 'Z', 'N', 'AO', 'F', 'opacity', 'motionvector','UV',
                                               'crypto_asset', 'crypto_material', 'crypto_object']:
                        menu.addAction(setAllLightGroupOnItemAction)
                        menu.addAction(setAllLightGroupOffItemAction)

                elif self.parent.objectName() == 'AOVLightGroupWidget':
                    slLightItemAction = QAction(u'选中对应的灯光', menu)
                    slLightItemAction.triggered.connect(self.parent.select_aov_light)
                    menu.addAction(slLightItemAction)

            except Exception as error:
                print(error)
                # logger.exception(error)
        else:
            pass

        return menu

    def check_select_item(self):
        items = self.selectedItems()
        for item in items:
            item.setCheckState(Qt.Checked)
            # item.setCheckState(Qt.Unchecked)

    def uncheck_select_item(self):
        items = self.selectedItems()
        for item in items:
            # item.setCheckState(Qt.Checked)
            item.setCheckState(Qt.Unchecked)

    def remove_aov_select_item(self):
        texts = self.selected_texts()
        utils.removeAOVs(texts)
        self.update()
        #
        # for text in texts:
        #     aov_node = 'aiAOV_%s' % text
        #     if cmds.objExists(aov_node):

    def adjustment_enbal(self):
        texts = self.selected_texts()
        for text in texts:
            aov_node = 'aiAOV_%s' % text
            if cmds.objExists(aov_node):
                cmds.editRenderLayerAdjustment("%s.enabled" % aov_node)

    def select_aov(self):
        texts = self.selected_texts()
        cmds.select(cl=1)
        for text in texts:
            aov_node = 'aiAOV_%s' % text
            if cmds.objExists(aov_node):
                cmds.select(aov_node, add=1)

    def set_all_lightgroup(self, value):
        texts = self.selected_texts()
        # cmds.select(cl=1)
        for text in texts:
            aov_node = 'aiAOV_%s' % text
            if cmds.objExists(aov_node):
                cmds.setAttr('%s.lightGroups' % aov_node, value)
        self.update()

    def dropEvent(self, event):
        """
        This event handler is called when the drag is dropped on this widget.
        # 定义鼠标松开事件
        :type event: QtWidgets.QDropEvent
        :rtype: None
        """
        # 定义鼠标松开事件
        # item = self.itemAt(event.pos())
        selectedItems = self.selectedItems()
        mimeData = event.mimeData()
        print('slitem', selectedItems)
        if event.mimeData().hasUrls:
            event.setDropAction(Qt.CopyAction)
            event.accept()
            mimeData.setText(selectedItems[0].text())
            # file_path_list = [str(url.toLocalFile()) for url in event.mimeData().urls()]
            print(event.mimeData().text())
            # self.dropped.emit(file_path_list)
        else:
            event.ignore()

        # if selectedItems and item:
        #     if self.treeWidget().isSortByCustomOrder():
        #         self.moveItems(selectedItems, item)
        #     else:
        #         msg = "You can only re-order items when sorting by custom order."
        #         # logger.info(msg)
        #
        # if item:
        #     item.dropEvent(event)
        #
        # self.itemDropped.emit(event)

    # def dragMoveEvent(self, event):
    #     """
    #     This event handler is called if a drag is in progress.
    #     # 定义鼠标拖拽移动事件
    #     :type event: QtGui.QDragMoveEvent
    #     :rtype: None
    #     """
    #     mimeData = event.mimeData()
    #
    #     if (mimeData.hasText() or mimeData.hasUrls()) and self.dropEnabled():
    #         event.accept()
    #     else:
    #         event.ignore()
    #
    # def dragEnterEvent(self, event):
    #     # 定义鼠标拖拽事件，必须的
    #     if event.mimeData().hasUrls:
    #         event.accept()
    #     else:
    #         event.ignore()


if __name__ == "__main__":
    app = QApplication([])
    my_ui = AovListWidget()
    my_ui.show()
    app.exec_()
